//
//  GoodsDetailCtr-cell.swift
//  smosky
//
//  Created by zhu xietong on 2018/5/21.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import Eelay
import soapp
import AsyncDisplayKit
open class GoodsInfoModeBar: JoView {
    open var changeMode:(ShopContentMode)->Void = {_ in}
}
extension GoodsDetailCtr{
    class TextNodeCell: JoCellNode {
        var textUI:LabelStyle{
            get{
                let ui = LabelStyle()
                _ = ui.font14
                //                ui.append(html_style: mo.model["atrribute.style",""])
                return ui
            }
        }
        
        let textL = JoTextNode()
        override func mo_model_reload() {
            view.backgroundColor = .white
            textL.attributedText = mo.model["content",""].ui.font14.lineSpace(7).cl_666.astring
        }
        
        override func specGetter() -> _Spec {
            return .inset([], [16], child: textL.Spec)
        }
    }
    
    open class ServerCell: JoCellNode {
        public let nameL = JoTextNode()
        public let textL = JoTextNode()
        var tags:[String] = []
        open override func mo_model_reload() {
            view.backgroundColor = ._background
            separatorHeight = TP.separatorHeight
            separatorColor = UIColor._separator
            let model = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            let lables = DataNode.path(node: "labels", model, value: NSMutableArray())
            var names = [String]()
            lables.list { (one:String, i) in
                names.append(one)
            }
            tags = names
            nameL.attributedText = "服务".loc.ui.font12.color(color: ._foregroundWeak).astring
            textL.attributedText = names.joined(separator: "·").ui.font12.lineSpace(7).color(color: ._foreground).astring
        }
        
        open override func specGetter() -> _Spec {
            if(tags.count > 0){
                return .inset([], [13,AppTheme.edge,11,AppTheme.edge], child: textL.Spec)

            }else{
                return .stack(["0"], childs: [])
            }
//            return .stack([[13,AppTheme.edge,11,AppTheme.edge],"h|16"], childs: [
//                nameL.Spec,
//                textL[_grow(1),_shrink(1)],
//                ])
        }
    }
    
    open class InfoCell: JoCellNode {
        public let tagBt = ASButtonNode()
        public let nameL = JoTextNode()
        
        public let priceL = ASTextNode()
        
        public let postL = JoTextNode()
        public let numL = JoTextNode()
        public let locationL = JoTextNode()
        
        public let preKit = PrebuyTipKit()
        
        open override func specGetter() -> _Spec {
            
            let overTag:_Spec = .over([], over: .stack([[-2,0,0,0]], childs: [
                tagBt.Spec
                ]), back: nameL.Spec)
            
            let w = (Swidth - 2.0 * AppTheme.edge)/3.0
            let bt_spec:_Spec = .stack(["h",&-.center,_justfy(.space_between),_nowrap,(Swidth-2*AppTheme.edge)], childs: [
//                postL[w,_grow(1)],
                numL[w,_grow(1)],
                locationL[w,_grow(1)]
                ])
            switch activeType {
            case .prebuy:
                let sep:_Spec = .stack([[16,AppTheme.edge],"v|10",_justfy(.space_between)], childs: [
                    overTag,
                    priceL.Spec,
                    preKit.Spec,
                    bt_spec
                    ])
                return sep
            default:
                break
            }
            let sep:_Spec = .stack([[16,AppTheme.edge],"v|10",_justfy(.space_between)], childs: [
                overTag,
                priceL.Spec,
                bt_spec
                ])
            return sep
        }
        
        var activeType:Goods.ActiveType = .none
        
        open override func mo_model_reload() {
            backgroundColor = ._background
            //            separatorHeight = TP.separatorHeight
            separatorColor = UIColor.clear
            let model = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            activeType = Goods.ActiveType(item: model)
            print("+++______+KA",activeType)
            switch activeType {
            case .prebuy:
                preKit.mo.model = model
            default:
                break
            }
            let price = model[float:"marketprice",0]
            let old_price = model[float:"productprice",0]
            let priceStr = "¥  ".ui.font11.color(color: ___shop.second).astring + (price.price_display + "   ").ui.color(color: ___shop.second).font20.astring
            
            if price < old_price
            {
                let old_priceStr = ("¥ " +  old_price.price_display).ui.color(hex: "#aaa").font12.append(.strikethroughStyle, 1).append(.strokeColor, UIColor(shex:"#aaa")).astring
                priceL.attributedText = (priceStr + old_priceStr)
            }
            else{
                priceL.attributedText = priceStr
            }
            
            postL.attributedText = "\("快递".loc)：\("包邮".loc)".ui.font11.color(color: ._foregroundWeak).astring
            numL.attributedText = "\("月销量".loc)：\(model["sales","0"])\(model["unit",""])".ui.font11.color(color: ._foregroundWeak).center.astring
            
            let str = "\(model["province",""])-\(model["city",""])"
            locationL.attributedText = str.ui.font11.color(color: ._foregroundWeak).right.astring
            locationL.textNode.maximumNumberOfLines = 1
            
            let merchID = model.possible("merchid","merch.id", default: "")
            
            if merchID == "0"
            {
                let tagStr = Goods.self_operated_tag
                let tagAtr = "\(tagStr)".ui.font(font: UIFont.systemFont(ofSize: 9)).color(hex: "#fff").astring
                tagBt.setAttributedTitle(tagAtr, for: .normal)
                tagBt.backgroundColor = UIColor(shex: "#E15378")
                tagBt.contentEdgeInsets = [2,4,3,4]
                nameL.textNode.maximumNumberOfLines = 3
                nameL.attributedText = "\(tagStr)   ".ui.lineSpace(7).font10.color(color: .clear).astring + model.possible("subtitle","title", default: "").ui.font12.color(color: ._foregroundWeak).lineSpace(7).astring
            }else{
                nameL.textNode.maximumNumberOfLines = 3
                tagBt.backgroundColor = .clear
                nameL.attributedText =  model.possible("subtitle","title", default: "").ui.font12.color(color: ._foregroundWeak).lineSpace(7).astring
                
                
            }
        }
    }
    
    
    
    class ImageCell: JoCellNode {
        let imgV = JoImageNode()
        
        override func addLayoutRules() {
            
            imgV.completionHandler = {[weak self]
                r in
                guard let ws = self else {
                    return
                }
                switch r {
                case .success(let result):
                    if ws.mo.model["__height__","XX"] != "XX"{
                        return
                    }
                    
                    let image = result.image
                    let h = (image.size.height/image.size.width) * ws.imgV.bounds.width
                    ws.mo.model["__height__"] = h
                    ws.active(ID: EeWebContainner.updateWebHeightKey, object: ws.mo.model)
                case .failure(let error):
                    break
                }
            }
           
                
//            imgV.completionHandler = {[weak self] (img, err, type, url) in
//
//                guard let image = img,let ws = self else {
//                    return
//                }
//
//            }
            backgroundColor = .white
            
        }
        
        override func mo_model_reload() {
            imgV.img_url = mo.model["content",""]
            //            imgV.networkImageNode.contentMode = .scaleToFill
            //            imgV.imageNode.contentMode = .scaleToFill
            
            
        }
        override func specGetter() -> _Spec {
            let h = mo.model["__height__","0"]
            let ispec = imgV[(Swidth-2.0*AppTheme.edge),h]
            
            let spec:_Spec = .inset([], [(AppTheme.edge/2.0),AppTheme.edge], child:  ispec)
            return spec
        }
    }
    
    open class Segbar:GoodsInfoModeBar,EeActionDelegate{
        public func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
            
        }
        
        public class Kit: RuleCell {
            let titleL = UILabel()
            let indicator = UIView()
            override public func addLayoutRules() {
                contentView.eelay = [
                    [indicator,[ee.L.B.R],"3"],
                    [titleL,[ee.X.Y,[0,-1]]],
                ]
                backgroundColor = .white
                _ = titleL.ui.font11.center.cl_333
            }
            override public func mo_model_reload() {
                titleL.text = mo.model["name",""]
                
                if mo.model[FK.selected,""] == FK.YES
                {
                    indicator.backgroundColor = ___shop.second
                }
                else{
                    indicator.backgroundColor = UIColor.table_bg_color
                }
            }
        }
        
        public let listV:RuleView<Kit> = RuleView<Kit>()
        override open func addLayoutRules() {
            let line = UIView()
            eelay = [
                [listV,[ee.T.L.B.R],"40"],
                //                [line,[ee.T.L.R],"\(TP.separatorHeight)"]
            ]
            line.backgroundColor = UIColor.separator_color
            
            listV.space = (0,0)
            listV.que_num = 2
            listV.limit_width = Swidth
            listV.item_height = 40
            listV.mo.model = ["options":
                ShopContentMode.segbar
                ].mutable_dictionary
            
            self.frame = [0,0,Swidth,40]
            
            listV.touchAction = {[weak self]
                cell,id,data in
                self?.reloadBar(data: data)
            }
        }
        
        
        open func reloadBar(data:NSMutableDictionary)  {
            if data[FK.selected,""] == FK.YES{
                return
            }
            let options = DataNode.path(node: "\(listV.options_node)", listV.mo.model, value: NSMutableArray())
            options.list { (one:NSMutableDictionary, i) in
                if one["id",""] == data["id",""]{
                    one[FK.selected] = FK.YES
                }
                else{
                    one[FK.selected] = FK.NO
                }
            }
            listV.mo_model_reload()
            if let mode = ShopContentMode(rawValue: data["id",""])
            {
                changeMode(mode)
            }
            
            
        }
        
    }
}

